﻿namespace SvCore.Tcp;

public partial class SvTcp
{
    public Dictionary<uint, Func<MyPackage, int>> DictAction = new Dictionary<uint, Func<MyPackage, int>>();
    public Dictionary<uint, string> DictMethod = new Dictionary<uint, string>();
    public void AddController<T>(T t)
    {
        if (t == null)
        {
            return;
        }
        Type type = t.GetType();
        var methods = type.GetMethods();
        foreach (var method in methods)
        {
            uint pid = CoreHash.HashMsg(method.Name);
            try
            {
                var act = (Func<MyPackage, int>)Delegate.CreateDelegate(typeof(Func<MyPackage, int>), t, method);
                DictAction[pid] = act;
                DictMethod[pid] = method.Name;
            }
            catch
            {
                loger.Warn($"注册 方法 出错：{method.Name} 出错");
            }
        }
    }
    public void Exec(MyPackage pack)
    {
        if (DictAction.TryGetValue((uint)pack.ProtocolId, out var api))
        {
            loger.Debug($"<-Exec pid: {pack.ProtocolId} {DictMethod[pack.ProtocolId]} ecode: {pack.Ecode} {pack.ECode}");
            try
            {
                api(pack);
            }
            catch (Exception e)
            {
                loger.Warn($"处理 Tcp消息 出错：{pack.ProtocolId} 出错", e);
            }
        }
        else
        {
            loger.Warn($"未注册 Tcp消息：{pack.ProtocolId} ");
        }
    }
}